#include <stdlib.h>
#include <stdio.h>
#include "myfunc.h"

int main(int argc, char **argv)
{
    int total_IO = 0;
    // make index
    Index(300, 16, INDEX_R, &total_IO);
    Index(400, 32, INDEX_S, &total_IO);
    int select_IO = 0;
    // select
    struct Tuple tuple;
    int index_addr = INDEX_S;
    int cur_pos = 0;
    int i = 0, j = 0, start;
    Buffer buf_index, buf_write, buf_disk;
    char temp[9] = {0};
    unsigned char *blk_index;
    unsigned char *blk_write;
    unsigned char *blk_disk;
    initBuffer(72, 64, &buf_index);
    initBuffer(72, 64, &buf_write);
    initBuffer(72, 64, &buf_disk);
    blk_index = readBlockFromDisk(index_addr, &buf_index);
    blk_write = getNewBlockInBuffer(&buf_write);
    GetTuple(&tuple, 0, blk_index);
    cur_pos++;
    // get S.C=50
    while (tuple.first != 50)
    {
        if (cur_pos == 7)
        {
            index_addr++;
            freeBlockInBuffer(blk_index, &buf_index);
            blk_index = readBlockFromDisk(index_addr, &buf_index);
            cur_pos = 0;
            GetTuple(&tuple, cur_pos, blk_index);
        }
        else
        {
            GetTuple(&tuple, cur_pos, blk_index);
        }
        cur_pos++;
    }
    start = tuple.second;
    blk_disk = readBlockFromDisk(start, &buf_disk);
    cur_pos = 0;
    GetTuple(&tuple, cur_pos, blk_disk);
    while (tuple.first != 50)
    {
        cur_pos++;
        GetTuple(&tuple, cur_pos, blk_disk);
    }
    while (tuple.first == 50)
    {
        memcpy(blk_write + i * 8, blk_disk + cur_pos * 8, 8);
        i++;
        if (i == 7)
        {
            // printf("mark\n");
            writeBlockToDisk(blk_write, RESULT3 + j, &buf_write);
            j++;
            i = 0;
            memset(blk_write, 0, 64);
        }
        if (cur_pos == 6)
        {
            start++;
            freeBlockInBuffer(blk_disk, &buf_disk);
            blk_disk = readBlockFromDisk(start, &buf_disk);
            cur_pos = 0;
            GetTuple(&tuple, cur_pos, blk_disk);
            if (tuple.first == 50)
            {
                memcpy(blk_write + i * 8, blk_disk + cur_pos * 8, 8);
                i++;
            }
            cur_pos++;
        }
        else
        {
            cur_pos++;
            GetTuple(&tuple, cur_pos, blk_disk);
        }
    }
    if (i > 0)
    {
        writeBlockToDisk(blk_write, RESULT3 + j, &buf_write);
    }
    select_IO += (buf_disk.numIO + buf_index.numIO + buf_write.numIO);
    total_IO += select_IO;
    printf("select IO:%d, total IO:%d\n", select_IO, total_IO);
    return 0;
}